<template>
  <div :class="{fullscreen:fullscreen}" class="tinymce-container" :style="{width:containerWidth}">
    <textarea :id="tinymceId" class="tinymce-textarea" :disabled="disabled"/>
    <div class="editor-custom-btn-container">
      <editorImage color="#1890ff" class="editor-upload-btn" @successCBK="imageSuccessCBK" :disabled="disabled"/>
    </div>
  </div>
</template>

<script>
/**
 * docs:
 * https://panjiachen.github.io/vue-element-admin-site/feature/component/rich-editor.html#tinymce
 */
import editorImage from './components/EditorImage'
import plugins from './plugins'
import toolbar from './toolbar'
import load from './dynamicLoadScript'
import { fileUpload } from '@/api/components'

const VUE_APP_API = process.env.VUE_APP_API
const VUE_APP_FILE = process.env.VUE_APP_FILE

// why use this cdn, detail see https://github.com/PanJiaChen/tinymce-all-in-one
const tinymceCDN =
  'https://cdn.jsdelivr.net/npm/tinymce-all-in-one@4.9.3/tinymce.min.js'

export default {
  name: 'Tinymce',
  components: { editorImage },
  props: {
    id: {
      type: String,
      default: function() {
        return (
          'vue-tinymce-' +
          +new Date() +
          ((Math.random() * 1000).toFixed(0) + '')
        )
      }
    },
    value: {
      type: String,
      default: ''
    },
    isEdit: {
       type: Boolean,
      default: true
    },
    toolbar: {
      type: Array,
      required: false,
      default() {
        return [
          'searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent blockquote undo redo removeformat subscript superscript formatselect hr numlist pagebreak',
          'fontsizeselect fontselect bullist insertdatetime table emoticons forecolor backcolor preview fullscreen'
         /* 'searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample formatselect hr',
          'fontsizeselect fontselect bullist numlist link charmap anchor pagebreak insertdatetime image media table emoticons forecolor backcolor preview fullscreen'*/
        ]
      }
    },
    menubar: {
      type: String,
      // default: ''
      default: 'file edit insert view format table tools'
    },
    height: {
      type: [Number, String],
      required: false,
      default: 300
    },
    width: {
      type: [Number, String],
      required: false,
      default: 'auto'
    },
    maxSize: {
      type: Number,
      default: null
    },
    disabled: {
      type: Boolean,
      default: false
    },
    addNum: {
      type: Number(),
      default: 0
    }
  },
  data() {
    return {
      hasChange: false,
      hasInit: false,
      tinymceId: this.id,
      fullscreen: false,
      languageTypeList: {
        en: 'en',
        zh: 'zh_CN',
        es: 'es_MX',
        ja: 'ja'
      }
    }
  },
  computed: {
    containerWidth() {
      const width = this.width
      if (/^[\d]+(\.[\d]+)?$/.test(width)) {
        // matches `100`, `'100'`
        return `${width}px`
      }
      return width
    }
  },
  watch: {
    value(val) {
      if(val == ''){
        this.hasChange = true
      }
      if (!this.hasChange && this.hasInit) {
        this.$nextTick(() => window.tinymce.get(this.tinymceId).setContent(val))
      }
      this.hasChange = false
    },
    isEdit(val){
      if(!val) {
        this.hasChange = false
        this.$nextTick(() => window.tinymce.get(this.tinymceId).setContent(''))
      } else {
        this.$nextTick(() => window.tinymce.get(this.tinymceId).setContent(this.value))
      }
    },
    addNum() {
      if(this.value == ''){
        this.$nextTick(() => window.tinymce.get(this.tinymceId).setContent(' '))
      }
    }
  },
  mounted() {
    this.init()
  },
  activated() {
    if (window.tinymce) {
      this.initTinymce()
    }
  },
  deactivated() {
    this.destroyTinymce()
  },
  destroyed() {
    this.destroyTinymce()
  },
  methods: {
    init() {
      // dynamic load tinymce from cdn
      load(tinymceCDN, err => {
        if (err) {
          this.$message.error(err.message)
          return
        }
        this.initTinymce()
      })
    },
    initTinymce() {
      const _this = this
      window.tinymce.init({
        selector: `#${this.tinymceId}`,
        branding: false,
        language: this.languageTypeList['zh'],
        height: this.height,
        body_class: 'panel-body',
        object_resizing: false,
        toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
        fontsize_formats: '10px 11px 12px 14px 18px 24px 36px',
        menubar: this.menubar.length > 0 ? this.menubar : menubar,
        plugins: plugins,
        end_container_on_empty_block: true,
        powerpaste_word_import: 'clean',
        code_dialog_height: 450,
        code_dialog_width: 1000,
        advlist_bullet_styles: 'square',
        advlist_number_styles: 'default',
        default_link_target: '_blank',
        // skin: 'lightgray',
        link_title: false,
        nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
        init_instance_callback: editor => {
          if (_this.value) {
            editor.setContent(_this.value)
          }
          _this.hasInit = true
          editor.on('NodeChange Change KeyUp SetContent', () => {
            this.hasChange = true
            this.$emit('input', editor.getContent())
          })
        },
        setup(editor) {
          editor.on('FullscreenStateChanged', e => {
            _this.fullscreen = e.state
          })
        },
        // 整合七牛上传
        // images_dataimg_filter(img) {
        //   setTimeout(() => {
        //     const $image = $(img)
        //     $image.removeAttr('width')
        //     $image.removeAttr('height')
        //     if ($image[0].height && $image[0].width) {
        //       $image.attr('data-wscntype', 'image')
        //       $image.attr('data-wscnh', $image[0].height)
        //       $image.attr('data-wscnw', $image[0].width)
        //       $image.addClass('wscnph')
        //     }
        //   }, 0)
        //   return img
        // },
        images_upload_handler(blobInfo, succFun, failFun) {
          // debugger
          if (_this.maxSize) {
            let file = blobInfo.blob()
            const fileLength = (file.size / 1024 / 1024).toFixed(2)
            if (fileLength > _this.maxSize) {
              // _this.$message({
              //   message:
              // '上传图片大小超过' +
              // _this.maxSize +
              // 'M，此图片大小为' +
              // fileLength +
              // '，请重新选择图片',
              //   type: 'error',
              //   duration: 3000
              // })
              // return false
              failFun(
                `上传图片大小超过${_this.maxSize}M，此图片大小为${fileLength}，请重新选择图片`
              )
            }
          }
          console.log(blobInfo)
          var xhr, formData
          var file = blobInfo.blob() //转化为易于理解的file对象
          xhr = new XMLHttpRequest()
          xhr.withCredentials = false
          xhr.open('POST', VUE_APP_API + '/jcdSys/jcdDataUpload/fileUpload')
          xhr.onload = function() {
            var json
            if (xhr.status != 200) {
              failFun('HTTP Error: ' + xhr.status)
              return
            }
            console.log(xhr.responseText)
            console.log(xhr.status)
            const imgUrl = JSON.parse(xhr.responseText).data
            if (!imgUrl || typeof imgUrl != 'string') {
              failFun('Invalid imgUrl: ' + imgUrl)
              return
            }
            succFun(VUE_APP_FILE + '/' + imgUrl)
          }
          formData = new FormData()
          formData.append('file', file, file.name) //此处与源文档不一样
          xhr.send(formData)
        }
      })
    },
    destroyTinymce() {
      const tinymce = window.tinymce.get(this.tinymceId)
      if (this.fullscreen) {
        tinymce.execCommand('mceFullScreen')
      }

      if (tinymce) {
        tinymce.destroy()
      }
    },
    resetContent() {
      this.hasChange = false
    },
    setContent(value) {
      window.tinymce.get(this.tinymceId).setContent(value)
    },
    getContent() {
      window.tinymce.get(this.tinymceId).getContent()
    },
    imageSuccessCBK(arr) {
      const _this = this
      arr.forEach(v => {
        window.tinymce
          .get(_this.tinymceId)
          .insertContent(`<img class="wscnph" src="${v.url}" >`)
      })
    }
  }
}
</script>

<style scoped>
.tinymce-container {
  position: relative;
  line-height: normal;
}
.tinymce-container >>> .mce-fullscreen {
  z-index: 10000;
}
.tinymce-container >>> .mce-menubtn.mce-fixed-width span {
  width: 50px;
}
.tinymce-textarea {
  visibility: hidden;
  z-index: -1;
}
.editor-custom-btn-container {
  position: absolute;
  right: 4px;
  top: 4px;
  /*z-index: 2005;*/
}
.fullscreen .editor-custom-btn-container {
  z-index: 10000;
  position: fixed;
}
.editor-upload-btn {
  display: inline-block;
}
</style>
